package com.hualan.sfzy.controller;

import com.hualan.sfzy.utils.OSSUtil;
import com.hualan.sfzy.utils.Result;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传、文件下载、文件预览控制层
 */
@RestController
public class FileController {
    @PostMapping("/upload")
    public Result fileUpload(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("请选择文件!");
        }
        // 获取上传的文件的文件名
        String fileName = file.getOriginalFilename();
        // 处理文件重名问题: 截取文件扩展名，用UUID替代文件名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString() + suffix;
        // 当前日期文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateDirPath = sdf.format(new Date());

        // 文件上传的最终路径
        String url = "";
        //实现上传功能
        try {
            url = OSSUtil.upload(dateDirPath + "/" + fileName, file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return Result.success(url);
    }

//    @RequestMapping("/download")
//    public void fileDownload(String filePath, HttpServletResponse response,
//                             HttpSession session) throws IOException {
//        // 创建输入流，读取文件
//        FileInputStream fis = new FileInputStream(rootPath + "/" + filePath);
//        // 设置响应头信息
//        response.setHeader("Content-Disposition", "attachement;filename=" +
//                filePath.substring(filePath.lastIndexOf("/") + 1));
//        // 获取输出流
//        ServletOutputStream out = response.getOutputStream();
//        // 拷贝
//        IOUtils.copy(fis, out);
//    }

}